package org.jeecg.modules.chexk.controller;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.chexk.entity.KuybChexk;
import org.jeecg.modules.chexk.service.IKuybChexkService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.chexk.vo.*;
import org.jeecg.modules.chexkChex.entity.KuybChexkChex;
import org.jeecg.modules.chexkChex.service.IKuybChexkChexService;
import org.jeecg.modules.chexkModel.entity.KuybChexkModel;
import org.jeecg.modules.chexkModel.service.IKuybChexkModelService;
import org.jeecg.modules.chexkPinp.entity.KuybChexkPinp;
import org.jeecg.modules.chexkPinp.service.IKuybChexkPinpService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

/**
 * @Description: 车型库
 * @Author: jeecg-boot
 * @Date: 2021-09-09
 * @Version: V1.0
 */
@Api(tags = "车型库")
@RestController
@RequestMapping("/chexk/kuybChexk")
@Slf4j
public class KuybChexkController extends JeecgController<KuybChexk, IKuybChexkService> {
    @Autowired
    IKuybChexkModelService kuybChexkModelService;

    @Autowired
    IKuybChexkChexService kuybChexkChexService;

    @Autowired
    private IKuybChexkService kuybChexkService;

    @Autowired
    IKuybChexkPinpService kuybChexkPinpService;

    @GetMapping(value = "/checkValiBrandData")
    public Result<?> checkValiBrandData() {
        kuybChexkPinpService.list().forEach(item -> {
            System.out.println(item.getId());
            KuybChexkChex kuybChexkChex = kuybChexkChexService.getOne(new LambdaQueryWrapper<KuybChexkChex>().eq(KuybChexkChex::getPinpid, item.getId()), false);
            if(kuybChexkChex == null) {
                kuybChexkPinpService.removeById(item);
                log.info(item.getName());
            }
        });

        return Result.OK();
    }

    @GetMapping(value = "/checkValiSeriesData")
    public Result<?> checkValiSeriesData() {
        kuybChexkChexService.list().forEach(item -> {
            KuybChexkModel kuybChexkModel = kuybChexkModelService.getOne(new LambdaQueryWrapper<KuybChexkModel>().eq(KuybChexkModel::getChex, item.getId()), false);
            if(kuybChexkModel == null) {
                kuybChexkChexService.removeById(item);
                log.info(item.getChexmc());
            }
        });

        return Result.OK();
    }

    @PostMapping(value = "/baiduOcrCarData")
    public Result<?> baiduOcrCarData(String type, HttpServletRequest request) {
        OcrCarData ocrCarData = kuybChexkService.baiduOcrCarData(type, request);
        if (ocrCarData != null) {
            if (ocrCarData.getVinCode() == null || ocrCarData.getVinCode().equals("") || ocrCarData.getVinCode().length() < 17)
                return Result.error("识别失败");
            return Result.OK(ocrCarData);
        } else
            return Result.error("识别失败");
    }

    String getPinpName(String pinPId) {
        KuybChexkPinp kuybChexkPinp = kuybChexkPinpService.getById(pinPId);
        if(kuybChexkPinp != null)
            return kuybChexkPinp.getName();

        return "";
    }

    KuybChexkChex getChexName(String chexId) {
        KuybChexkChex kuybChexkChex = kuybChexkChexService.getById(chexId);
        if(kuybChexkChex != null)
            return kuybChexkChex;

        return null;
    }

    @GetMapping(value = "/queryChelxqByVin")
    public Result<?> queryChelxqByVin(String vin) {
        VinChelxq vinChelxq = kuybChexkService.queryChelxqByVin(vin);
        if (vinChelxq != null) {
            if(vinChelxq.getCode() != null && vinChelxq.getCode().equals(0)) {
                String amVehicleId = vinChelxq.getResult().get(0).getAmVehicleId();
                log.info("车型库id: %", amVehicleId);
                KuybChexkModel kuybChexkModel = kuybChexkModelService.getById(amVehicleId);
                if(kuybChexkModel != null) {
                    Map map = new HashMap();
                    KuybChexkChex kuybChexkChex = getChexName(kuybChexkModel.getChex());
                    map.put("fullName", kuybChexkChex.getChexmc() + " " + getPinpName(kuybChexkChex.getPinpid()) + " " + kuybChexkModel.getChexmc());
                    map.put("price", kuybChexkModel.getJiag());
                    map.put("carid", kuybChexkModel.getId());
                    map.put("nengylx", kuybChexkModel.getNengylx());

                    return Result.OK(map);
                }
                else
                    return Result.error("本地车型库，没有查到数据");

            } else
                return Result.error("vin码查询车型id失败");
        }
        else
            return Result.error("queryChelxqByVin异常");
    }

    @Cacheable(value = "getBrandList")
    @GetMapping(value = "/getBrandList")
    public Result<?> getBrandList() {
//        return Result.OK(kuybChexkPinpService.list().stream().filter(f->f.getInitial().equals("B")).collect(Collectors.groupingBy(KuybChexkPinp::getInitial)));
        List list = new ArrayList();
        kuybChexkPinpService.list().stream().collect(Collectors.groupingBy(KuybChexkPinp::getInitial)).forEach((key, value) -> {
            Map<String, Object> map = new HashMap<>();
            map.put("letter", key);
            map.put("data", value);

            list.add(map);
        });

        return Result.OK(list);
    }

    @Cacheable(value = "getSeriesList", key = "#brandId")
    @GetMapping(value = "/getSeriesList")
    public Result<?> getSeriesList(String brandId) {
//        return Result.OK(kuybChexkService.getSeriesList(brandId));

        List<Series> out = new ArrayList<>();

        List<KuybChexkChex> list = kuybChexkChexService.list(new LambdaQueryWrapper<KuybChexkChex>().eq(KuybChexkChex::getPinpid, brandId));
        Map<String, List<KuybChexkChex>> map = list.stream().collect(Collectors.groupingBy(KuybChexkChex::getFenl));
        map.forEach((key, value) -> {
            Series series = new Series();
            series.setName(key);
            List<SubSeries> subSeriesList = new ArrayList<>();
            value.forEach(item -> {
                SubSeries subSeries = new SubSeries();
                subSeries.setId(item.getId());
                subSeries.setName(item.getChexmc());
                subSeries.setShifjk(item.getShifjk());
                subSeriesList.add(subSeries);
            });

            series.setList(subSeriesList);
            out.add(series);
        });

        return Result.OK(out);
    }

    @Cacheable(value = "getModelList", key = "#seriesId")
    @GetMapping(value = "/getModelList")
    public Result<?> getModelList(String seriesId) {
//        List list = kuybChexkService.getModelList(seriesId);
        List list = kuybChexkModelService.list(new LambdaQueryWrapper<KuybChexkModel>().eq(KuybChexkModel::getChex, seriesId));
        if (list != null && list.size() > 0) {
            List<ModelEx> out = new ArrayList();
            //Map<String, List<Model>> map = kuybChexkService.getModelList(seriesId).stream().collect(Collectors.groupingBy(Model::getYeartype));
            List<KuybChexkModel> tempList = kuybChexkModelService.list(new LambdaQueryWrapper<KuybChexkModel>().eq(KuybChexkModel::getChex, seriesId));
            Map<String, List<KuybChexkModel>> map = tempList.stream().collect(Collectors.groupingBy(KuybChexkModel::getNinak));
            for (Map.Entry entry : map.entrySet()
            ) {
                ModelEx modelEx = new ModelEx();
                modelEx.setYeartype(entry.getKey() + "");
                List<Model> list1 = new ArrayList<>();
                List<KuybChexkModel> list2 = (List<KuybChexkModel>)entry.getValue();
                list2.forEach(item -> {
                    Model model = new Model();
                    model.setId(item.getId());
                    model.setName(item.getChexmc());
                    model.setPrice(item.getJiag() + "");
                    model.setYeartype(item.getNinak());
                    model.setNengylx(item.getNengylx());

                    list1.add(model);
                });

                modelEx.setList(list1);
                out.add(modelEx);
            }

            Collections.sort(out, new Comparator<ModelEx>() {
                @Override
                public int compare(ModelEx o1, ModelEx o2) {
                    return Integer.parseInt(o2.getYeartype()) - Integer.parseInt(o1.getYeartype());
                }
            });

            return Result.OK(out);
        } else
            return Result.error(500, "没查到数据");
    }

    @GetMapping(value = "/getChexkByModelId")
    public Result<?> getChexkByModelId(String modelId) {
        List<Brand> list = kuybChexkService.getBrandList();
        return Result.error("没有查到数据");
    }

    /**
     * 分页列表查询
     *
     * @param kuybChexk
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "车型库-分页列表查询")
    @ApiOperation(value = "车型库-分页列表查询", notes = "车型库-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(KuybChexk kuybChexk,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<KuybChexk> queryWrapper = QueryGenerator.initQueryWrapper(kuybChexk, req.getParameterMap());
        Page<KuybChexk> page = new Page<KuybChexk>(pageNo, pageSize);
        IPage<KuybChexk> pageList = kuybChexkService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param kuybChexk
     * @return
     */
    @AutoLog(value = "车型库-添加")
    @ApiOperation(value = "车型库-添加", notes = "车型库-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody KuybChexk kuybChexk) {
        kuybChexkService.save(kuybChexk);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param kuybChexk
     * @return
     */
    @AutoLog(value = "车型库-编辑")
    @ApiOperation(value = "车型库-编辑", notes = "车型库-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody KuybChexk kuybChexk) {
        kuybChexkService.updateById(kuybChexk);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "车型库-通过id删除")
    @ApiOperation(value = "车型库-通过id删除", notes = "车型库-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        kuybChexkService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "车型库-批量删除")
    @ApiOperation(value = "车型库-批量删除", notes = "车型库-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.kuybChexkService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "车型库-通过id查询")
    @ApiOperation(value = "车型库-通过id查询", notes = "车型库-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        KuybChexk kuybChexk = kuybChexkService.getById(id);
        if (kuybChexk == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(kuybChexk);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param kuybChexk
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, KuybChexk kuybChexk) {
        return super.exportXls(request, kuybChexk, KuybChexk.class, "车型库");
    }

    String getPinyin(String china) {
        HanyuPinyinOutputFormat formart = new HanyuPinyinOutputFormat();
        formart.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        formart.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        formart.setVCharType(HanyuPinyinVCharType.WITH_V);
        char[] arrays = china.trim().toCharArray();
        String result = "";
        try {
            for (int i=0;i<arrays.length;i++) {
                char ti = arrays[i];
                if(Character.toString(ti).matches("[\\u4e00-\\u9fa5]")){ //匹配是否是中文
                    String[] temp = PinyinHelper.toHanyuPinyinStringArray(ti,formart);
                    result += temp[0];
                }else{
                    result += ti;
                }
            }
        } catch (BadHanyuPinyinOutputFormatCombination e) {
            e.printStackTrace();
        }

        return result;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(String type, HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象

            try {
                List<Chexk4Import> list = ExcelImportUtil.importExcel(file.getInputStream(), Chexk4Import.class, new ImportParams());

                // 清理不用的品牌
                if(type.equals("11")) {
                    kuybChexkPinpService.list().forEach(item -> {
                        if(!list.stream().filter(f->f.getZhupp().equals(item.getName())).findFirst().isPresent()) {
                            System.out.println(item.getName());

                            kuybChexkPinpService.removeById(item.getId());
                        }
                    });
                }

                // 品牌
                if(type.equals("1")) {
                    Set<Chexk4Import> set = new TreeSet<>(Comparator.comparing(Chexk4Import::getZhupp));
                    set.addAll(list);
                    set.forEach(item -> {
                        KuybChexkPinp kuybChexkPinp = new KuybChexkPinp();
                        kuybChexkPinp.setId(item.getPinpId());
                        kuybChexkPinp.setName(item.getZhupp());
//                        String shouzm = getPinyin(item.getZhupp());
//                        shouzm = shouzm.substring(0, 1);
//                        shouzm = shouzm.toUpperCase();
//                        kuybChexkPinp.setInitial(shouzm);
                        kuybChexkPinp.setInitial(item.getShouzm());
                        kuybChexkPinp.setLogo(item.getZhut());

                        try {
                            kuybChexkPinpService.save(kuybChexkPinp);

                        } catch (Exception error) {
                            log.error(error.getMessage());
                        }
                    });
                }

                // 车系
                if(type.equals("2")) {
                    List batch = new ArrayList();
                    Set<Chexk4Import> setChexi = new TreeSet<>(Comparator.comparing(Chexk4Import::getChexId));
                    setChexi.addAll(list);
                    setChexi.forEach(item -> {
                        KuybChexkChex  kuybChexkChex = new  KuybChexkChex();
                        kuybChexkChex.setId(item.getChexId());
                        kuybChexkChex.setPinpid(item.getPinpId());
                        kuybChexkChex.setFenl(item.getPinp());
                        kuybChexkChex.setChexmc(item.getChex());
                        kuybChexkChex.setShifjk(item.getShifjk() != null && item.getShifjk().indexOf("进口") >=0 ? "1" : "0");

                        batch.add(kuybChexkChex);
                    });

                    try {
                        kuybChexkChexService.saveBatch(batch, 5000);

                    } catch (Exception error) {
                        log.error(error.getMessage());
                    }
                }

                // 车型
                if(type.equals("3")) {
                    List batch = new ArrayList();
                    list.forEach(item -> {
                        log.info(item.getCheknf());
                        if(item.getCheknf() == null || Integer.parseInt(item.getCheknf()) < 2010)
                            return;

                        KuybChexkModel kuybChexkModel = new KuybChexkModel();
                        kuybChexkModel.setPinpId(item.getPinpId());
                        kuybChexkModel.setChex(item.getChexId());
                        kuybChexkModel.setId(item.getModelId());
                        kuybChexkModel.setChexmc(item.getChekmc());
                        kuybChexkModel.setNinak(item.getCheknf());
                        kuybChexkModel.setJiag(Double.parseDouble(item.getZhidj()) / 10000);
                        kuybChexkModel.setShifjk(item.getShifjk() != null && item.getShifjk().indexOf("进口") >= 0 ? 1 : 0);
                        String zhengczb = item.getZhengczb();
                        kuybChexkModel.setYuancbx(zhengczb);

                        try {
                            String a = zhengczb.substring(0, zhengczb.indexOf("年"));
                            switch (a) {
                                case "八":
                                    a = "8";
                                    break;
                                case "两":
                                    a = "2";
                                    break;
                                case "六":
                                    a = "6";
                                    break;
                                case "七":
                                    a = "7";
                                    break;
                                case "三":
                                    a = "3";
                                    break;
                                case "十":
                                    a = "10";
                                    break;
                                case "四":
                                    a = "4";
                                    break;
                                case "五":
                                    a = "5";
                                    break;
                                case "一":
                                    a = "1";
                                    break;
                            }

                            kuybChexkModel.setYuancbxnx(Integer.parseInt(a));
                            String b = zhengczb.substring(zhengczb.indexOf("或") + 1, zhengczb.indexOf("万"));
                            kuybChexkModel.setYuancbxgls(Integer.parseInt(b) * 10000);

                        } catch (Exception error) {
                            ;
                        }

                        String nengylx = item.getNegylx();
                        if (nengylx != null) {
                            if (nengylx.indexOf("汽油") >= 0)
                                nengylx = "1";
                            if (nengylx.indexOf("混") >= 0)
                                nengylx = "2";
                            if (nengylx.indexOf("纯电") >= 0)
                                nengylx = "3";
                            if(nengylx.indexOf("柴油") >= 0)
                                nengylx = "4";
                            if(nengylx.indexOf("增程") >= 0)
                                nengylx = "5";

                            kuybChexkModel.setNengylx(nengylx);
                        }

                        batch.add(kuybChexkModel);
                    });

                    kuybChexkModelService.saveBatch(batch, 5000);
                }

                System.out.println("导入完成");

            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());

            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return null;
    }

    Map<String, String> fastCheXObject = null;

    private String getChexId(String chex) {
        if(fastCheXObject == null) {
            fastCheXObject = new HashMap<>();
            kuybChexkChexService.list().forEach(item -> {
                fastCheXObject.put(item.getChexmc(), item.getId());
            });
        }

        return fastCheXObject.get(chex);
    }

    private String getPinpId(String zhupp) {
        KuybChexkPinp kuybChexkPinp = kuybChexkPinpService.getOne(new LambdaQueryWrapper<KuybChexkPinp>().eq(KuybChexkPinp::getName, zhupp), false);
        if(kuybChexkPinp != null) {
            return kuybChexkPinp.getId();
        }

        return null;
    }

}
